How change the color of the individual button from gray to black onClick and how to assign the "key" prop on React?
I get this message "Warning: Each child in a list should have a unique "key" prop." even though I already assign the key. And how to change the color of the individual buttons from gray to black (not all of the buttons). Here's my code. I'm using react.
Square.js
import React from 'react';
export default function Square(props) {
const square = {
width: "100px",
height: "100px",
color:"yellow",
backgroundColor: props.shade
};
return (
<button className={"square " + props.shade}
onClick={props.onClick}
style={square}
key={props.value}>{props.value}
</button>
);
}
Board.js
import Square from './Square.js';
import React from 'react';
export default class Board extends React.Component {
constructor(props){
super(props);
this.state ={
temp:"",
colorB:"black",
}
}
color=()=> {
this.setState({ temp: this.state.colorB})
this.setState({ colorB: this.state.temp})
}
renderSquare(key, squareShade) {
return <Square
shade = {squareShade}
onClick={this.color}
/>
}
render() {
const board = [];
for(let i = 0; i < 8; i++){
const squareRows = [];
for(let j = 0; j < 8; j++){
const squareShade = (isEven(i) && isEven(j)) || (!isEven(i) && !isEven(j))? this.state.temp : this.state.colorB;
squareRows.push(<Square
shade = {squareShade}
onClick={this.color}
key={(i*8 + j).toString()} //the key
value={(i*8 + j).toString()}
/>);
}
board.push(<div className="board-row">{squareRows}</div>)
}
return (
<div>
{board}
</div>
);
}
}
function isEven(num){
return num % 2 === 0
}
/*
Some of the codes are referenced from: https://www.techighness.com/post/develop-two-player-chess-game-with-react-js/
*/
Even though is easy to put a i inside the key attribute, never use the index value as key. The index is not unique and can conflict between components.
use something like key={squareRows.id} instead. Provide some unique id without the index value.